/**
 * 路由鉴权
 */

import router from "@/router/index.js"
import store from "@/store"

import { asyncRouter } from "@/router/index.js" // 导入动态路由名单

// 进度条
import nprogress from "nprogress"
import "nprogress/nprogress.css"

const whiteList = ["/login", '/404']  // 跳转白名单组件

// 前置守卫
router.beforeEach(async (to, from, next) => {
  nprogress.start() // 开启进度条
  if (store.getters.token) {  // 已登录
    if (to.path === "/login") {
      next('/')
      nprogress.done()
      return
    }
    if (!store.getters.userId) { // 没有用户信息 
      const { roles } = await store.dispatch('user/userInfoActions')  // 获取用户信息
      const filterRoutes = asyncRouter.filter(item => { // 帅选出可访问路由
        return roles.menus.includes(item.name)  // 是否包含
      })
      router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
      store.commit('user/setRoutes', filterRoutes)  // 设置用户可访问路由
      next(to.path)
    } else {
      next()
    }
  } else {  // 未登录
    if (!whiteList.includes(to.path)) {
      next('/login')
      nprogress.done()
      return
    }
    next()
  }
})

// 后置守卫
router.afterEach((to, from) => {
  nprogress.done()  // 关闭进度条
})